'''
Created on Dec 11, 2009

@author: anch
'''
import os.path
import sqlite3

FILE_DB = "strategy.db3"
DB_FILE_PATH = None
_training_mode = False
proccessing_queue = []
_debug = False

def getDatabaseFile():
	global DB_FILE_PATH
	if DB_FILE_PATH == None:
		DB_FILE_PATH = os.path.join(\
			os.path.dirname(__file__), FILE_DB)
	return DB_FILE_PATH

class DbAgent(object):
	'''
	classdocs
	'''
	__SQL_UPDATE_NORMAL = "INSERT OR REPLACE INTO normal VALUES (?, ?, ?, ?, ?)"


	def __init__(self):
		'''
		Constructor
		'''
	
	@staticmethod
	def fetchDbInfoByState(tbl_name, str_state):
		conn = sqlite3.connect(getDatabaseFile())
		conn.text_factory = str
		c = conn.cursor()
		c.execute("select * from {0} where state=?".format(tbl_name), (sqlite3.Binary(str_state),))
		row = c.fetchone()
		
#		if row == None:
#			return AnchDatabaseAgent.generateNewEntity(self.state, self.myself)
#		else:
#			AnchTournamentPlayer.__hit_counter+=1
#			return AnchDatabaseAgent.generateExistedEntity(self.state, self.myself, row)
		
		conn.close()
		return row
	
	def updateDataBase(self):
		pass
	
	@staticmethod
	def getNormalPieceProbs(code_pattern):
		db_row = NS.fetchDbInfoByState('normal', code_pattern)
		if db_row == None:
			db_entry = NormalPieceStrategyItem.createNewByPattern(code_pattern)
		else:
			db_entry = NormalPieceStrategyItem.createByDbResult(code_pattern, db_row)
			pass
		
		if _training_mode:
			proccessing_queue.append(db_entry)
		return db_entry
		
class NormalPieceStrategyItem(object):
	def __init__(self, state, probs):
		'''
		Constructor
		'''
		self.state = state
		self.probs = probs
	
	@staticmethod
	def createNewByPattern(code_pattern):
		if code_pattern[3] == "\x00":
			probs = [33.333333333333336] * 3 + [0]
		else:
			probs = [25] * 4
		return NormalPieceStrategyItem(code_pattern, probs)
	
	@staticmethod
	def createByDbResult(code_pattern, db_row):
		if code_pattern[3] == "\x00":
			probs = list(db_row[1:4]) + [0]
		else:
			probs = db_row[1:5]
		return NormalPieceStrategyItem(code_pattern, probs)
		
	

NS = DbAgent
		